type ScanParams = {
  /** 广播扫码动作名 */
  scanActive: string
  /** 广播标签名 */
  scanValue: string
  /** 扫码间隔 默认200ms */
  scanInterval?: number
  /** 扫码回调 */
  scanCallback: (code: string) => void
}

let main = null
let intentFilter = null
let filter = null
let receiver = null
let scanFlag = null

const setFilter = (scanActive: ScanParams['scanActive']) => {
  filter = new intentFilter()
  filter.addAction(scanActive) // 换你的广播动作
}

const setReceiver = (params: ScanParams) => {
  const { scanCallback, scanInterval = 200 } = params
  receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
    onReceive: function (context, intent) {
      plus.android.importClass(intent)
      const code = intent.getStringExtra(params.scanValue) // 换你的广播标签
      // 防重复
      if (scanFlag) return false
      scanFlag = true
      setTimeout(function () {
        scanFlag = false
        scanCallback(code)
      }, scanInterval)
    },
  })
}

const startScan = () => {
  if (!main || !receiver || !filter) return console.error('main or filter or receiver is null')
  main?.registerReceiver(receiver, filter)
}

const stopScan = () => {
  if (!main || !receiver) return console.error('main or receiver is null')
  main?.unregisterReceiver(receiver)
}

/** 扫码 */
const useScan = (params: ScanParams) => {
  /* #ifdef APP */
  if (!params) throw new Error('params is required')
  const { scanActive, scanValue, scanCallback } = params

  const updateFilter = () => {
    console.log('watchEffect')
    if (scanActive && scanValue) {
      setFilter(scanActive)
      setReceiver(params)
      startScan()
    }
  }

  console.log('onLoad = scan')
  if (!main) main = plus.android.runtimeMainActivity()
  if (!intentFilter) intentFilter = plus.android.importClass('android.content.IntentFilter')
  watchEffect(updateFilter)

  onShow(() => {
    console.log('onShow = scan')
    startScan()
  })
  onUnload(() => {
    console.log('onUnload = scan')
    stopScan()
  })
  onHide(() => {
    console.log('onHide = scan')
    stopScan()
  })
  return {
    stopScan,
    updateFilter,
  }
  /* #endif */
}

export default useScan
